package javax.realtime;

import javax.realtime.RealtimeThread.RealtimeThreadState;

public class Thread extends java.lang.Thread{

	private Runnable thread;
	public Thread(Runnable thread)
	{
		super();
		this.thread = thread;
	}
	public Runnable getRunnable()
	{
		return thread;
	}
	
	@Override
	public void run()
	{
		if(thread instanceof RealtimeThread)
		{
			((RealtimeThread)thread).setTID(NativeHelper.gettid());
			
			NativeHelper.sched_setaffinity(0, ((RealtimeThread)thread).getCurrentCPU());
			if(((RealtimeThread)thread).getSchedulingParameters() instanceof PriorityParameters)
			{
				NativeHelper.setpriority(((RealtimeThread)thread).getTID(), ((PriorityParameters)((RealtimeThread)thread).getSchedulingParameters()).getPriority());
			}
			
			((RealtimeThread)thread).setRealtimeThreadState(RealtimeThreadState.RTT_WAITING);
			//if(((RealtimeThread)thread).getStartTime().compareTo(((RealtimeThread)thread).getStartTime().getClock().getTime()) > 0);			//only if we have OneShotTimer...
			/*
			synchronized(this)
			{
				try {
					this.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}*/

			((RealtimeThread) thread).setRealtimeThreadState(RealtimeThreadState.RTT_RUNNING);
		}
		thread.run();
		if(thread instanceof RealtimeThread)
		{
			RealtimeThread rtt = (RealtimeThread)thread;
			rtt.stopTimer();
			rtt.setRealtimeThreadState(RealtimeThreadState.RTT_TERMINATED);
			Scheduler scheduler = rtt.getScheduler();
			if(scheduler instanceof esrc.c9cf.Scheduler)
			{
				esrc.c9cf.Scheduler esrcScheduler = (esrc.c9cf.Scheduler)scheduler;
				esrcScheduler.removeFromFeasibilitySet((RealtimeThread)thread);
				esrcScheduler.reschedule();
			}
		}
	}
}
